<template>
  <div class="app-container">
    <div style="border: 1px gainsboro solid;padding: 25px 10px 10px 30px">
      <el-form :model="form" ref="queryForm" size="small" :inline="true" v-show="showSearch" >
        <div style="display: inline-block;width: 330px;">
          <span style="color:red;line-height:2.3;padding: 5px">*</span>
          <el-form-item label="供应商：" prop="supplierId">
            <el-select v-model="form.supplierId" @keyup.enter.native="handleQuery" clearable>
              <el-option v-for="supplier in SupplierList" :key="supplier.id" :value="supplier.id" :label="supplier.name">{{supplier.name}}</el-option>
            </el-select>
          </el-form-item>
        </div>
<!--        <div style="display: inline-block;width: 300px;">-->
<!--          <el-form-item label="收支方式" prop="sheetType" >-->
<!--            <el-select v-model="form.sheetType" :disabled="this.SettleFeeSheetList != 0"  clearable>-->
<!--              <el-option :value="1" label="应收款">应收款</el-option>-->
<!--              <el-option :value="2" label="应付款">应付款</el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </div>-->
        <br/>
        <div  v-if="this.$route.query.id != null">
          <div style="display: inline-block;width: 415px;">
            <el-form-item label="状态：" prop="status" style="display: inline-block;width: 300px;margin-left: 30px">
              <span :style="{color: statusColor}">
                {{ form.status==0 ? '待审核' : (form.status==3 ? '审核通过' : '审核拒绝') }}
              </span>
            </el-form-item>
          </div>
          <div style="display: inline-block;width: 400px;" v-if="form.refuseReason!=null && form.refuseReason!=''">
            <el-form-item label="拒绝原因：" prop="refuseReason" style="display: inline-block;width: 400px;margin-left: 1px">
              <input type="text" style="background-color: #FFFFFF;height: 30px;width: 220px;border-radius: 5px;margin-left: 10px;border: 1px gainsboro solid;" disabled v-model="form.refuseReason">
            </el-form-item>
          </div><br/>
          <div style="display: inline-block;width: 400px;margin-left: 16px">
            <el-form-item label="操作人：" prop="createBy" style="display: inline-block;width: 400px;color:rgb(100, 100, 100);">
              {{ form.createBy }}
            </el-form-item>
          </div>
          <div style="display: inline-block;width: 400px;margin-left: 1px">
            <el-form-item label="操作时间：" prop="createTime" style="display: inline-block;width: 400px;color:rgb(100, 100, 100);">
              {{ form.createTime }}
            </el-form-item>
          </div><br/>
          <div style="display: inline-block;width: 400px;margin-left: 16px" v-if="form.approveBy!=null">
            <el-form-item label="审核人：" prop="approveBy" style="display: inline-block;width: 400px;color:rgb(100, 100, 100);">
              {{ form.approveBy }}
            </el-form-item>
          </div>
          <div style="display: inline-block;width: 400px;margin-left: 1px"  v-if="form.approveTime!=null">
            <el-form-item label="审核时间：" prop="approveTime" style="display: inline-block;width: 400px;color:rgb(100, 100, 100);">
              {{ form.approveTime }}
            </el-form-item>
          </div>
        </div>
        </el-form>
    </div>
    <div>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="payTypeAdd"
            style="width: 80px;height: 30px;margin-top: 10px"
            v-hasPermi="['system:SettleFeeSheet:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            style="width: 80px;height: 30px;margin-top: 10px"
            @click="handleDelete('pay')"
          >删除</el-button>
        </el-col>
      </el-row>
    </div>
    <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px">
      <el-form ref="form" :model="form1" :rules="rules" label-width="80px" >
        <el-table :data="SettlePreSheetList" height="300px" ref="tblPurchaseOrderDetail" @selection-change="handlePaySelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="项目" prop="itemId" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.itemId" @keyup.enter.native="handleQuery" clearable>
                <el-option v-for="(type,index) in SettleOutItem" :key="index" :value="type.id" :label="type.name">{{type.name}}</el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="金额" prop="amount" width="300" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.amount" placeholder="请输入金额" @input="getSumNumber"/>
            </template>
          </el-table-column>
          <el-table-column>

          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <div style="border: 1px gainsboro solid;padding: 10px">
      <h3 style="margin:0 0 15px 10px;font-weight: bolder;">合计</h3>
      <div style="display: inline-block;margin-left:50px">
        总金额：<input type="text" style="background-color: #FFFFFF;height: 30px;width: 220px;border-radius: 5px;margin-left: 10px;border: 1px gainsboro solid;text-align: right" disabled v-model="this.totalAmount" @change="getSumNumber">
      </div>
    </div>
    <div style="border: 1px gainsboro solid;padding: 10px;text-align: right">
      <label >备注： </label>
      <textarea v-model="form.description" style="width: 90%;height: 50px;margin-top: 10px;margin-left: 10px;margin-bottom: 10px;border-radius: 5px;vertical-align:middle;border: 1px gainsboro solid"/>
    </div>

    <div slot="footer" class="dialog-footer" style="text-align: center;margin: 5px">
      <el-button type="primary" @click="submitForm(0)">保 存</el-button>
      <el-button type="primary" @click="submitForm(3)" v-if="this.$route.query.id==null">审核通过</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import {parseTime} from "../../../utils/ruoyi";
import {listSettlePreSheet,getSettlePreSheet,updateSettlePreSheet,addSettlePreSheet} from "@/api/system/SettlePreSheet";
import {listUser} from "@/api/system/user";
import {listSupplier} from "@/api/system/Supplier";
import {listSettleOutItem} from "@/api/system/SettleOutItem";
//日期转换
function formatDateToBackend(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

export default {
  name: "SettlePreSheetAdd",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 支付方式选中数组
      payIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 含税总金额
      totalAmount: 0,
      //状态颜色
      statusColor: "rgb(100, 100, 100)",
      //用户列表
      UserList: [],
      //收支方式
      SettlePreSheetList: [],
      // 供应商列表
      SupplierList: [],
      // 应付款
      SettleOutItem: [],
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        scName: null,
        customerName: null,
      },
      // 订单支付参数
      orderPayTypeParams: {
        orderId: null
      },
      // 支付参数
      payTypeParams: {},
      // 表单参数
      form: {
        id: null,
        code: null,
        supplierId: null,
        totalAmount: null,
        description: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null,
        approveBy: null,
        approveTime: null,
        status: null,
        refuseReason: null,
        settleStatus: null,
        settlePreSheetDetailList:[]
      },
      form1: {
        sheetId: null,
        itemId: null,
        amount: null,
      },
      // 根据订单ID查询订单支付方式
      payType: {
        orderId: null,
      },
      SettlePreSheetAllList: [],

      //供应商费用
      SettlePreSheet:[],
      SettlePreSheet2:[],
    };
  },
  created() {
    this.getList();
    //用户数据
    this.getUserList();
    //供应商数据
    this.getSupplierList();

    this.settleOutItemList();

    if (this.$route.query.id!=null){
      this.selectOrder();
    }


    this.loading = false;
  },
  methods: {
    parseTime,

    /** 查询采购订单列表 */
    getList() {
      this.SettlePreSheet=[];
      var list=[];
      listSettlePreSheet({}).then(response => {
        this.SettlePreSheet2=response.rows;
        list=response.rows;
        for (var i=0;i<list.length;i++){
          this.SettlePreSheet.push(list[i].id);
        }
      });
    },

    /** 查询用户列表 */
    getUserList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.UserList = response.rows;
      });
    },
    /** 查询供应商列表 */
    getSupplierList() {
      this.loading = true;
      listSupplier(this.queryParams).then(response => {
        this.SupplierList = response.rows;
      });
    },

    /** 应付款 */
    settleOutItemList() {
      this.loading = true;
      listSettleOutItem(this.queryParams).then(response => {
        this.SettleOutItem = response.rows;
      });
    },

    /** 查询订单详情 */
    selectOrder() {
      const id = this.$route.query.id
      getSettlePreSheet(id).then(response => {
        // 订单赋值
        this.form = response.data;
        this.SettlePreSheetList = response.data.settlePreSheetDetailList;


        this.loading = false;

        //状态值颜色判断
        if (response.data.status == 0){
          this.statusColor = "rgb(100, 100, 100)";
        }else if (response.data.status==3){
          this.statusColor = "rgb(82, 196, 26)";
        }else {
          this.statusColor = "rgb(255, 0, 0)";
        }

        this.getSumNumber();
      });
    },

    /** 查询订单支付方式 */
    getSumNumber() {
      const list = this.SettlePreSheetList;

      this.totalAmount = 0;

      for (var i = 0; i < list.length; i++) {
        this.totalAmount += Number(list[i].amount);
      }

      this.form.totalAmount = this.totalAmount;
    },
    // 取消按钮
    cancel() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.back();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        supplierId: null,
        totalAmount: null,
        description: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null,
        approveBy: null,
        approveTime: null,
        status: null,
        refuseReason: null,
        settleStatus: null
      };
      this.form1 = {
        sheetId: null,
        itemId: null,
        amount: null,
      };
      this.resetForm("form");
    },

    // 多选框选中数据
    handlePaySelectionChange(selection) {
      this.payIds = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
    },
    /** 提交按钮 */
    submitForm(status) {
      if (this.formInfo()) {
        if (this.form.id != null) {
          this.form.settlePreSheetDetailList=this.SettlePreSheetList;
          this.form.updateBy = "系统管理员";
          this.form.updateById = 1;
          this.form.updateTime = formatDateToBackend(new Date());
          updateSettlePreSheet(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.back();
          });
        } else {
          const newId = generateUniqueId(this.SettlePreSheet);
          const Code = getOrderCode(this.SettlePreSheet2);
          this.form.id = newId;
          this.form.code = Code;
          for (var i = 0; i < this.SettlePreSheetList.length; i++) {
            this.SettlePreSheetList[i].sheetId = newId;
          }
          this.form.settlePreSheetDetailList=this.SettlePreSheetList;
          this.form.createBy = "系统管理员";
          this.form.createById = "1";
          this.form.totalAmount = this.totalAmount;
          this.form.status = status;
          if (status == 3) {
            this.form.approveBy = '系统管理员';
            this.form.approveTime = formatDateToBackend(new Date());
          }
          addSettlePreSheet(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.back();
          });
        }
      }
    },
    //提交表单验证
    formInfo() {
      if (this.form.supplierId == null || this.form.supplierId == '') {
        this.$modal.msgError("请选择供应商");
        return false;
      }
      if (this.SettlePreSheetList.length == 0){
        this.$modal.msgError("请录入项目");
        return false;
      }

      //支付方式验证
      for (var j = 0; j < this.SettlePreSheetList.length; j++) {
        if (this.SettlePreSheetList[j].itemId == null || this.SettlePreSheetList[j].itemId == '') {
          this.$modal.msgError("请选择项目");
          return false;
        } else if (this.SettlePreSheetList[j].amount == null || this.SettlePreSheetList[j].amount == '') {
          this.$modal.msgError("请输入金额");
          return false;
        } else if (this.SettlePreSheetList[j].amount <= 0) {
          this.$modal.msgError("第"+ (j + 1) +"行金额必须为数字");
          return false;
        }
        //金额必须是数字或者小数
        if (!/^[0-9]+\.?[0-9]*$/.test(this.SettlePreSheetList[j].amount)) {
          this.$modal.msgError("第"+ (j + 1) +"行金额必须为数字");
          return false;
        }
      }

      const arr = this.SettlePreSheetList; // 假设 this.array 是 Vue 数据中的数组
      for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
          if (arr[i].itemId == arr[j].itemId) {
            this.$modal.msgError("第"+ (i + 1) +"行项目与其他行重复，请检查！");
            return false; // 发现重复
          }
        }
      }

      return true;
    },
    /** 删除按钮操作 */
    handleDelete() {
       if (this.SettlePreSheetList.length === 0) {
          this.$message.warning('请选择要删除的行');
          return;
        }
        this.SettlePreSheetList = this.SettlePreSheetList.filter(item => !this.payIds.includes(item.id));
        this.payIds = [];
        this.getSumNumber(); // 重新计算合计
        console.log(this.SettlePreSheetList);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/SettleInItem/export', {
        ...this.queryParams
      }, `SettleInItem_${new Date().getTime()}.xlsx`)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },

    //支付方式添加
    payTypeAdd() {

      if (this.form.supplierId == null || this.form.supplierId == '') {
        this.$modal.msgError("请选择供应商");
        return false;
      }

      const newId = generateUniqueId(this.SettlePreSheetAllList);
      this.SettlePreSheetAllList.push(newId);
      this.SettlePreSheetList.push({
        id: newId,
        sheetId: null,
        itemId: null,
        amount: null,
      })
    },
  },
  beforeRouteLeave(to, from, next) {
    // 设置一个标志，表示需要刷新数据
    to.meta.b = true;
    next();
  }
};

// ID生成
function generateUniqueId(existingIds) {
  const prefix = '18';
  const length = 19 - prefix.length;
  const characters = '0123456789';
  let uniqueId;

  do {
    uniqueId = prefix;
    for (let i = 0; i < length; i++) {
      uniqueId += characters.charAt(Math.floor(Math.random() * characters.length));
    }
  } while (existingIds.includes(uniqueId));

  return uniqueId;
}


//单号生成
function getOrderCode(list) {
  var date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1, // 月份是从0开始的
    day = date.getDate();

// 如果月份或日期是个位数，在前面补0
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;

  var time=year + '' + month + '' + day

  let type="GYSYFK"; //供应商应付款
  var code=time+'0000000'
  var str1=code.slice(0,7)
  var str2=code.slice(7,)

  if (str2.slice(0,1)=="0"){
    str1=code.slice(0,6)
    str2=code.slice(6,)

    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(6,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(6,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(6,)
        }
      }
    }
  }else {
    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(7,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(7,)
        }
      }
    }
  }

  code=type+str1+(parseInt(str2)+1)

  return code.toString();
}
</script>

